package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aries.ui.view.radius.RadiusTextView;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.FragmentViewPagerAdapter;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpActivity;
import com.chexiehui.jc.entity.ForumInfo;
import com.chexiehui.jc.event.GlobalFollowForumEvent;
import com.chexiehui.jc.mvp.forum.ForumTribuneDetailsCovenant;
import com.chexiehui.jc.mvp.forum.ForumTribuneDetailsPresenter;
import com.chexiehui.jc.ui.fragment.ForumFollowHomeBbsFragment;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.widget.LoadingLayout;
import com.flyco.tablayout.SlidingTabLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 论坛详情
 */
public class ForumTribuneDetailsActivity extends BaseMvpActivity<ForumTribuneDetailsPresenter> implements ForumTribuneDetailsCovenant.View{

    @BindView(R.id.rtv_forum_count)
    RadiusTextView rtvForumCount;
    @BindView(R.id.rtv_forum_join)
    RadiusTextView rtvForumJoin;
    @BindView(R.id.tv_forum_introduce)
    TextView tvForumIntroduce;
    @BindView(R.id.ll_user_head_container)
    LinearLayout llUserHeadContainer;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.loadingLayout)
    LoadingLayout loadingLayout;
    @BindView(R.id.stl_action_table)
    SlidingTabLayout stl_action_table;
    @BindView(R.id.vp_action_pager)
    ViewPager vp_action_pager;
    private ForumInfo forumInfo;

    private String forumId;

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            forumId = bundle.getString("forumId");
        }
    }

    private String[] titles = new String[]{"动态", "精华"};
    private ArrayList<Fragment> actionFragmentList = new ArrayList<>();

    @Override
    protected void setTitleBar() {
        titleBar.setTitleMainText("")
                .setRightTextDrawable(0);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_forum_tribune_details;
    }

    @Override
    protected void initView(Bundle var1) {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setEnableOverScrollDrag(false);
        refreshLayout.setDisableContentWhenLoading(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableScrollContentWhenRefreshed(true);
        refreshLayout.setEnableOverScrollDrag(true);
        loadingLayout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadingLayout.setStatus(LoadingLayout.Loading);
                mvpPresenter.getForumInfo();
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(1000, true);
                ((ForumFollowHomeBbsFragment) actionFragmentList.get(vp_action_pager.getCurrentItem()))
                        .onParentPageCallRefresh();
            }
        });
        if (StringUtils.isTrimEmpty(forumId)) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText("没有找到任何数据");
        } else {
            loadingLayout.setStatus(LoadingLayout.Loading);
            mvpPresenter.getForumInfo();
        }
    }



    private void setContentPageInfo() {
        vp_action_pager.setOffscreenPageLimit(titles.length);
        for (int i = 0; i < titles.length; i++) {
            actionFragmentList.add(ForumFollowHomeBbsFragment.getInstance(forumId, i));
        }
        vp_action_pager.setAdapter(new FragmentViewPagerAdapter(getSupportFragmentManager(), actionFragmentList, titles));
        stl_action_table.setViewPager(vp_action_pager);
    }

    private void setHeadForumInfo() {
        titleBar.setTitleMainText(forumInfo.getName())
                .setRightTextDrawable(R.mipmap.ic_edit_post)
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        startActivity(ForumDynamicPostActivity.class, new BundleBuilder()
                                .putSerializable("forumInfo", forumInfo).create());
                    }
                });
        llUserHeadContainer.removeAllViews();
        for (int i = 0; i < forumInfo.getPhotoList().size(); i++) {
            ImageView ivHead = (ImageView) View.inflate(mContext, R.layout.item_only_head, null);
            llUserHeadContainer.addView(ivHead);
            GlideUtil.loadImageViewCircleCrop(mContext, forumInfo.getPhotoList().get(i),
                    ivHead, R.drawable.shape_circle, R.drawable.shape_circle);
        }
        rtvForumCount.setText(forumInfo.getFollowCount());
        rtvForumJoin.setSelected(forumInfo.isCollect());
        rtvForumJoin.setText(forumInfo.isCollect() ? "已加入" + forumInfo.getDay() + "天" : "加入");
        rtvForumJoin.setTag(-1);
        tvForumIntroduce.setText(forumInfo.getIntroduction());
    }

    @Override
    public void onGetForumInfoSuccess(BaseModel<ForumInfo> successResult) {
        if (loadingLayout.getStatus() != LoadingLayout.Success) {
            loadingLayout.setStatus(LoadingLayout.Success);
        }
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
        forumInfo = successResult.getData();
        setHeadForumInfo();
        if (actionFragmentList.size() <= 0) {
            setContentPageInfo();
        }
    }

    @Override
    public void onGetForumInfoFailure(BaseModel<Object> failureResult) {
        if (Constants.PAGE_DATA_EMPTY == failureResult.getResultCode()) {
            loadingLayout.setStatus(LoadingLayout.Empty);
            loadingLayout.setEmptyText(failureResult.getResultInfo());
        } else {
            loadingLayout.setStatus(LoadingLayout.Error);
            loadingLayout.setErrorText(failureResult.getResultInfo());
        }
    }

    @Override
    public String getForumId() {
        return forumId;
    }

    @Override
    protected ForumTribuneDetailsPresenter createPresenter() {
        return new ForumTribuneDetailsPresenter(this);
    }

    @Override
    public void onDoFollowForumSuccess(BaseModel<String> successResult) {
        EventBus.getDefault().post(new GlobalFollowForumEvent(successResult.getData(), !forumInfo.isCollect()));
    }

    @Override
    public void onDoFollowForumFailure(BaseModel<Object> failureResult) {
        showToast(failureResult.getResultInfo());
    }

    @Subscribe
    public void onGlobalFollowForumEvent(GlobalFollowForumEvent event) {
        if (event != null && !StringUtils.isTrimEmpty(event.getForumId())) {
            forumInfo.setCollect(event.isFollow());
            rtvForumJoin.setSelected(forumInfo.isCollect());
            rtvForumJoin.setText(forumInfo.isCollect() ? "已加入" + forumInfo.getDay() + "天" : "加入");
            tvForumIntroduce.setText(forumInfo.getIntroduction());
        }
    }

    @OnClick({R.id.rtv_forum_join})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.rtv_forum_join:
                mvpPresenter.doFollowForum(getForumId());
                break;
        }
    }

}
